package com.zxc.oj.ojcodesandbox;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.zxc.oj.ojcodesandbox.model.ExecuteCodeRequest;
import com.zxc.oj.ojcodesandbox.model.ExecuteCodeResponse;
import com.zxc.oj.ojcodesandbox.model.ExecuteMessage;
import com.zxc.oj.ojcodesandbox.model.JudgeInfo;
import com.zxc.oj.ojcodesandbox.utils.ProcessUtils;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class JavaDockerCodeSandboxOld {

    private final static String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private final static String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private final static Long TIME_OUT = 1000L;
    //获取默认的Docker Client
    public static final DockerClient dockerClient = DockerClientBuilder.getInstance().build();
    public static final String IMAGE = "openjdk:8-alpine";

    static {
//        //拉取镜像
//
//        PullImageCmd pullImageCmd = dockerClient.pullImageCmd(IMAGE);
//        PullImageResultCallback callback = new PullImageResultCallback() {
//            @Override
//            public void onNext(PullResponseItem item) {
//                System.out.printf("下载状态：" + item.getStatus());
//                super.onNext(item);
//            }
//        };
//        try {
//            pullImageCmd.exec(callback).awaitCompletion();
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        System.out.printf("下载完成");


    }


    public static void main(String[] args) {
//        JavaDockerCodeSandbox sandbox = new JavaDockerCodeSandbox();
//        ExecuteCodeRequest codeRequest = new ExecuteCodeRequest();
//        codeRequest.setInputList(Arrays.asList("1 2", "3 4"));
//        String code = ResourceUtil.readStr("./testCode/simpleComputeArge/Main.java", StandardCharsets.UTF_8);
//        codeRequest.setLanguage("java");
//        codeRequest.setCode(code);
//        ExecuteCodeResponse response = sandbox.executeCode(codeRequest);
//        System.out.println(response);

    }


    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        List<String> inputList = request.getInputList();
        String language = request.getLanguage();
        String code = request.getCode();

        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //判断目录是否存在，不存在则创建目录
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        //把用户代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        //编译代码，得到class文件
        String compileCmd = String.format("javac -encoding utf-8 -source 1.8 -target 1.8 %s", userCodeFile.getAbsolutePath());
        try {
            Process process = Runtime.getRuntime().exec(compileCmd);
            //等待程序执行获取错误码
            ExecuteMessage executeMessage = ProcessUtils.ProcessExecuteMessage(process, "编译");

            System.out.println("executeMessage1:" + executeMessage);
        } catch (Exception e) {
            return getErrorResponse(e);
        }


        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(IMAGE);
        //映射本地文件到容器中
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(100 * 1000 * 1000L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        //hostConfig.withSecurityOpts(Arrays.asList("seccomp="));
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));

        CreateContainerResponse containerResponse = containerCmd
                .withName("java-code-sandbox" + UUID.randomUUID())
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)
                .withReadonlyRootfs(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withAttachStderr(true)
                .withTty(true)
                .exec();
        String containerId = containerResponse.getId();

        System.out.println("containerId" + containerId);
        //启动容器
        dockerClient.startContainerCmd(containerId).exec();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        ExecuteMessage executeMessage = new ExecuteMessage();
        final String[] message = {null};
        final String[] errorMessage = {null};
        for (String inputArgs : inputList) {
            //定时器
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            //docker exec java-code-sandbox java -cp /app Main 1 2
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .withCmd(cmdArray)
                    .exec();
            System.out.println("创建执行命令：" + execCreateCmdResponse);
            String execId = execCreateCmdResponse.getId();
            final boolean[] timeout = {true};
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errorMessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    System.out.println();
                    super.onNext(frame);
                }
            };


            final long[] maxMemory = {0L};

            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            statsCmd.exec(new ResultCallback<Statistics>() {

                @Override
                public void close() throws IOException {

                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(Statistics statistics) {
                    Long usage = statistics.getMemoryStats().getUsage();
                    System.out.println("内存占用：" + usage);
                    maxMemory[0] = Math.max(maxMemory[0], usage);
                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }
            });


            try {
                stopWatch.start();
                dockerClient.execStartCmd(execId).exec(execStartResultCallback).awaitCompletion(TIME_OUT, TimeUnit.MICROSECONDS);
                stopWatch.stop();
                statsCmd.close();

            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            } finally {
                try {
                    execStartResultCallback.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setRunTime(stopWatch.getLastTaskTimeMillis());
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }
        try {
            Thread.sleep(TIME_OUT * 10);
            dockerClient.removeContainerCmd(containerId).withForce(true).exec();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        return executeCodeResponse;
    }

    /**
     * 获取错误响应
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        response.setOutputList(new ArrayList<>());
        response.setMessage(e.getMessage());
        //2 表示代码沙箱运行错误
        response.setStatus(2);
        response.setJudgeInfo(new JudgeInfo());

        return response;
    }
}
